<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="updateVisible"
    title="编辑测试步骤"
    width="700px"
    :before-close="handleClose"
    destroy-on-close
    class="edit-step-modal"
  >
    <div v-if="step" class="space-y-6">
      <!-- 步骤信息 -->
      <div class="flex items-center justify-between">
        <div class="flex items-center">
          <div class="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center text-sm mr-3 font-medium">
            {{ step.stepNumber }}
          </div>
          <div>
            <h4 class="font-medium text-gray-800">{{ step.description || '未知步骤' }}</h4>
            <p class="text-xs text-gray-500">类型: {{ getStepTypeLabel(step.type) }}</p>
          </div>
        </div>
        <div class="flex items-center">
          <span class="text-xs text-gray-500 mr-2">步骤状态:</span>
          <el-select v-model="stepData.status" size="small" style="width: 100px">
            <el-option label="待执行" value="pending" />
            <el-option label="执行中" value="running" />
            <el-option label="已成功" value="success" />
            <el-option label="已失败" value="failed" />
            <el-option label="已跳过" value="skipped" />
          </el-select>
        </div>
      </div>

      <!-- 步骤位置调整 -->
      <div class="flex items-center justify-between bg-gray-50 p-3 rounded-lg">
        <div class="flex items-center">
          <span class="text-xs text-gray-500 mr-2">步骤位置:</span>
          <div class="flex border border-gray-200 rounded-md">
            <el-button size="small" @click="moveStepUp" :disabled="!canMoveUp">
              <el-icon><i-ep-arrow-up /></el-icon>
            </el-button>
            <el-button size="small" @click="moveStepDown" :disabled="!canMoveDown">
              <el-icon><i-ep-arrow-down /></el-icon>
            </el-button>
            <el-button size="small" @click="moveStepToTop" :disabled="!canMoveUp">
              <el-icon><i-ep-top /></el-icon>
            </el-button>
            <el-button size="small" @click="moveStepToBottom" :disabled="!canMoveDown">
              <el-icon><i-ep-bottom /></el-icon>
            </el-button>
          </div>
        </div>
        <div class="flex items-center">
          <span class="text-xs text-gray-500 mr-2">跳转至位置:</span>
          <div class="flex">
            <el-input-number 
              v-model="targetPosition" 
              :min="1" 
              :max="totalSteps"
              size="small"
              style="width: 80px"
            />
            <el-button size="small" @click="moveStepToPosition" class="ml-1">
              <el-icon><i-ep-right /></el-icon>
            </el-button>
          </div>
        </div>
      </div>

      <!-- 配置选项卡 -->
      <div>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本设置" name="basic">
            <div class="space-y-4">
              <!-- 步骤名称 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">步骤名称</label>
                <el-input
                  v-model="stepData.description"
                  placeholder="输入步骤名称"
                  class="rounded-button"
                />
              </div>

              <!-- 元素定位器 (针对输入、点击、断言等操作) -->
              <div v-if="showSelector">
                <label class="block text-sm font-medium text-gray-700 mb-1">元素定位器</label>
                <div class="flex">
                  <el-input
                    v-model="stepData.selector"
                    placeholder="#username 或 .input-field"
                    class="rounded-l-button"
                  />
                  <el-button class="rounded-r-button border-l-0">
                    <el-icon><i-ep-aim /></el-icon>
                  </el-button>
                </div>
                <p class="mt-1 text-xs text-gray-500">支持 CSS 选择器、XPath 或 Playwright 定位器</p>
              </div>

              <!-- URL输入 (针对导航操作) -->
              <div v-if="step.type === 'navigation'">
                <label class="block text-sm font-medium text-gray-700 mb-1">URL</label>
                <el-input
                  v-model="stepData.url"
                  placeholder="https://example.com"
                  class="rounded-button"
                />
              </div>

              <!-- 输入值 (针对输入操作) -->
              <div v-if="step.type === 'input'">
                <label class="block text-sm font-medium text-gray-700 mb-1">输入文本</label>
                <el-input
                  v-model="stepData.value"
                  placeholder="要输入的文本内容"
                  class="rounded-button"
                />
              </div>

              <!-- 断言类型 (针对断言操作) -->
              <div v-if="step.type === 'assertion'">
                <label class="block text-sm font-medium text-gray-700 mb-1">断言类型</label>
                <el-select v-model="stepData.assertType" class="w-full rounded-button">
                  <el-option label="元素存在" value="exists" />
                  <el-option label="元素可见" value="visible" />
                  <el-option label="元素包含文本" value="text" />
                  <el-option label="元素值等于" value="value" />
                  <el-option label="URL包含" value="url" />
                  <el-option label="页面标题包含" value="title" />
                </el-select>
                <div class="mt-2">
                  <label class="block text-sm font-medium text-gray-700 mb-1">预期值</label>
                  <el-input
                    v-model="stepData.expectedValue"
                    placeholder="预期的文本或值"
                    class="rounded-button"
                  />
                </div>
              </div>

              <!-- 等待配置 (针对等待操作) -->
              <div v-if="step.type === 'wait'">
                <label class="block text-sm font-medium text-gray-700 mb-1">等待类型</label>
                <div class="grid grid-cols-2 gap-3 mb-3">
                  <div 
                    class="border rounded-lg p-3 cursor-pointer"
                    :class="stepData.waitType === 'element' ? 'border-primary bg-blue-50' : 'border-gray-200'"
                    @click="stepData.waitType = 'element'"
                  >
                    <el-radio v-model="stepData.waitType" value="element">等待元素</el-radio>
                  </div>
                  <div 
                    class="border rounded-lg p-3 cursor-pointer"
                    :class="stepData.waitType === 'time' ? 'border-primary bg-blue-50' : 'border-gray-200'"
                    @click="stepData.waitType = 'time'"
                  >
                    <el-radio v-model="stepData.waitType" value="time">固定时间</el-radio>
                  </div>
                </div>
                <div v-if="stepData.waitType === 'element'">
                  <label class="block text-sm font-medium text-gray-700 mb-1">等待条件</label>
                  <el-select v-model="stepData.waitCondition" class="w-full rounded-button">
                    <el-option label="元素可见" value="visible" />
                    <el-option label="元素隐藏" value="hidden" />
                    <el-option label="元素附加到DOM" value="attached" />
                    <el-option label="元素从DOM分离" value="detached" />
                  </el-select>
                </div>
                <div v-else>
                  <label class="block text-sm font-medium text-gray-700 mb-1">等待时间 (ms)</label>
                  <el-input-number 
                    v-model="stepData.waitTime" 
                    :min="100" 
                    :max="30000"
                    class="w-full"
                  />
                </div>
              </div>

              <!-- 截图配置 -->
              <div v-if="step.type === 'screenshot'">
                <label class="block text-sm font-medium text-gray-700 mb-1">截图类型</label>
                <div class="grid grid-cols-2 gap-3 mb-3">
                  <div 
                    class="border rounded-lg p-3 cursor-pointer"
                    :class="stepData.screenshotType === 'page' ? 'border-primary bg-blue-50' : 'border-gray-200'"
                    @click="stepData.screenshotType = 'page'"
                  >
                    <el-radio v-model="stepData.screenshotType" value="page">整个页面</el-radio>
                  </div>
                  <div 
                    class="border rounded-lg p-3 cursor-pointer"
                    :class="stepData.screenshotType === 'element' ? 'border-primary bg-blue-50' : 'border-gray-200'"
                    @click="stepData.screenshotType = 'element'"
                  >
                    <el-radio v-model="stepData.screenshotType" value="element">特定元素</el-radio>
                  </div>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">文件名</label>
                  <el-input
                    v-model="stepData.filename"
                    placeholder="screenshot"
                    class="rounded-button"
                  />
                </div>
              </div>

              <!-- 通用选项 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">超时时间 (ms)</label>
                <el-input-number 
                  v-model="stepData.timeout" 
                  :min="1000" 
                  :max="60000"
                  class="w-full"
                />
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="高级选项" name="advanced">
            <div class="space-y-4">
              <!-- 重试设置 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">重试设置</label>
                <div class="grid grid-cols-2 gap-3">
                  <div>
                    <label class="block text-xs text-gray-600 mb-1">重试次数</label>
                    <el-input-number v-model="stepData.retryCount" :min="0" :max="5" class="w-full" />
                  </div>
                  <div>
                    <label class="block text-xs text-gray-600 mb-1">重试间隔 (ms)</label>
                    <el-input-number v-model="stepData.retryInterval" :min="100" :max="5000" class="w-full" />
                  </div>
                </div>
              </div>

              <!-- 错误处理 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">错误处理</label>
                <div class="space-y-2">
                  <el-checkbox v-model="stepData.continueOnError">忽略错误并继续执行</el-checkbox>
                  <el-checkbox v-model="stepData.screenshotOnFailure">失败时截图</el-checkbox>
                </div>
              </div>

              <!-- 执行延迟 -->
              <div class="grid grid-cols-2 gap-3">
                <div>
                  <label class="block text-xs text-gray-600 mb-1">执行前延迟 (ms)</label>
                  <el-input-number v-model="stepData.delayBefore" :min="0" :max="10000" class="w-full" />
                </div>
                <div>
                  <label class="block text-xs text-gray-600 mb-1">执行后延迟 (ms)</label>
                  <el-input-number v-model="stepData.delayAfter" :min="0" :max="10000" class="w-full" />
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-between">
        <el-button type="danger" @click="deleteStep">
          <el-icon><i-ep-delete /></el-icon>
          删除步骤
        </el-button>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="saveStep">保存修改</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useScriptStore } from '../stores/script'
import { ElMessage, ElMessageBox } from 'element-plus'

// Element Plus 图标
import {
  ArrowUp as iEpArrowUp,
  ArrowDown as iEpArrowDown,
  Top as iEpTop,
  Bottom as iEpBottom,
  Right as iEpRight,
  Aim as iEpAim,
  Delete as iEpDelete
} from '@element-plus/icons-vue'

// Props & Emits
const props = defineProps({
  visible: Boolean,
  step: Object
})

const emit = defineEmits(['update:visible', 'confirm', 'delete', 'move'])

const scriptStore = useScriptStore()

// 处理 v-model
const updateVisible = (value) => {
  emit('update:visible', value)
}

// 响应式数据
const activeTab = ref('basic')
const targetPosition = ref(1)

// 步骤数据的副本，用于编辑
const stepData = ref({
  description: '',
  selector: '',
  url: '',
  value: '',
  status: 'pending',
  timeout: 5000,
  assertType: 'visible',
  expectedValue: '',
  waitType: 'element',
  waitCondition: 'visible',
  waitTime: 1000,
  screenshotType: 'page',
  filename: 'screenshot',
  retryCount: 0,
  retryInterval: 1000,
  continueOnError: false,
  screenshotOnFailure: false,
  delayBefore: 0,
  delayAfter: 0
})

// 计算属性
const totalSteps = computed(() => scriptStore.stepCount)

const canMoveUp = computed(() => props.step && props.step.stepNumber > 1)

const canMoveDown = computed(() => props.step && props.step.stepNumber < totalSteps.value)

const showSelector = computed(() => {
  return props.step && ['input', 'click', 'assertion'].includes(props.step.type)
})

// 在步骤变化时初始化数据
watch(() => props.step, (newStep) => {
  if (newStep) {
    stepData.value = {
      ...stepData.value,
      ...newStep,
      // 确保某些字段有默认值
      timeout: newStep.timeout || 5000,
      retryCount: newStep.retryCount || 0,
      retryInterval: newStep.retryInterval || 1000,
      continueOnError: newStep.continueOnError || false,
      screenshotOnFailure: newStep.screenshotOnFailure || false,
      delayBefore: newStep.delayBefore || 0,
      delayAfter: newStep.delayAfter || 0
    }
    targetPosition.value = newStep.stepNumber
  }
}, { immediate: true })

// 方法
const getStepTypeLabel = (type) => {
  const labels = {
    navigation: '页面导航',
    input: '输入文本',
    click: '点击元素',
    assertion: '验证断言',
    wait: '等待',
    screenshot: '截图'
  }
  return labels[type] || '未知类型'
}

const moveStepUp = () => {
  if (canMoveUp.value) {
    emit('move', props.step, props.step.stepNumber - 1)
  }
}

const moveStepDown = () => {
  if (canMoveDown.value) {
    emit('move', props.step, props.step.stepNumber + 1)
  }
}

const moveStepToTop = () => {
  if (canMoveUp.value) {
    emit('move', props.step, 1)
  }
}

const moveStepToBottom = () => {
  if (canMoveDown.value) {
    emit('move', props.step, totalSteps.value)
  }
}

const moveStepToPosition = () => {
  if (targetPosition.value >= 1 && targetPosition.value <= totalSteps.value && targetPosition.value !== props.step.stepNumber) {
    emit('move', props.step, targetPosition.value)
  }
}

const saveStep = async () => {
  try {
    emit('confirm', stepData.value)
    ElMessage.success('步骤已更新')
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message)
  }
}

const deleteStep = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除步骤 ${props.step.stepNumber}: ${props.step.description} 吗？`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    emit('delete', props.step)
    ElMessage.success('步骤已删除')
  } catch {
    // 用户取消删除
  }
}

const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style scoped>
.edit-step-modal :deep(.el-dialog__body) {
  padding: 20px;
}

.rounded-button {
  border-radius: 6px;
}

.rounded-l-button {
  border-top-left-radius: 6px;
  border-bottom-left-radius: 6px;
}

.rounded-r-button {
  border-top-right-radius: 6px;
  border-bottom-right-radius: 6px;
}
</style>
